<template>
  <div class="user-info-container">
    <h2>更新用户信息</h2>

    <el-card class="update-form-card">
      <el-form
        ref="userInfoFormRef"
        :model="userInfoForm"
        :rules="userInfoRules"
        label-width="100px"
        v-loading="loading"
      >
        <el-form-item label="用户名">
          <el-input v-model="userInfoForm.username" disabled />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="userInfoForm.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userInfoForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfoForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="userInfoForm.role" disabled />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmitUpdate">保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import userApi from '@/api/user'
import type { UserInfo, UpdateUserInfoParams } from '@/api/user'

const userInfoFormRef = ref<FormInstance>()
const userInfoForm = reactive<UserInfo>({
  userId: 0,
  username: '',
  realName: '',
  phone: '',
  email: '',
  role: '',
  status: 0,
  createdAt: '',
  updatedAt: '',
})
const loading = ref(false)

// Form validation rules (basic examples)
const userInfoRules = reactive<FormRules>({
  realName: [
    { max: 50, message: '姓名长度不能超过 50 个字符', trigger: 'blur' },
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
    { max: 100, message: '邮箱长度不能超过 100 个字符', trigger: 'blur' },
  ],
})

// Fetch current user info from localStorage
const fetchCurrentUserInfo = () => {
  const userInfoString = localStorage.getItem('userInfo')
  if (userInfoString) {
    try {
      const userInfo: UserInfo = JSON.parse(userInfoString)
      // Populate the form with current user info
      Object.assign(userInfoForm, userInfo)
      // Assuming role is stored as a key like 'admin' and you want to display a中文 name
      const roleMap = {
        admin: '管理员',
        manager: '经理',
        operator: '操作员',
      }
      userInfoForm.role = roleMap[userInfo.role as keyof typeof roleMap] || userInfo.role;
    } catch (error) {
      console.error('Failed to parse user info from localStorage:', error)
      ElMessage.error('获取用户信息失败，请重新登录')
      // Optionally redirect to login
      // router.push('/login')
    }
  } else {
     ElMessage.error('用户信息未找到，请重新登录')
     // Optionally redirect to login
     // router.push('/login')
  }
}

// Handle form submission for updating user info
const handleSubmitUpdate = async () => {
  if (!userInfoFormRef.value) return

  await userInfoFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // Prepare data to send, only include fields that can be updated
        const dataToSend: UpdateUserInfoParams = {
          realName: userInfoForm.realName,
          phone: userInfoForm.phone,
          email: userInfoForm.email,
        }

        const res = await userApi.updateUserInfo(dataToSend)
        if (res.data) {
          ElMessage.success('用户信息更新成功')
          // Update localStorage with the new info from the response
          localStorage.setItem('userInfo', JSON.stringify(res.data))
          // Refresh the form with updated data (optional, as localStorage is updated)
          // fetchCurrentUserInfo()
        } else {
           // Handle cases where code is 200 but data might be null or empty
           ElMessage.success(res.message || '用户信息更新成功')
             // Refresh localStorage from the form data if backend doesn't return updated user
           localStorage.setItem('userInfo', JSON.stringify({...userInfoForm}))
        }
      } catch (error: any) {
        console.error('Error updating user info:', error)
        ElMessage.error(error.response?.data?.message || '更新用户信息失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  fetchCurrentUserInfo()
})
</script>

<style scoped>
.user-info-container {
  padding: 20px;
}

.update-form-card {
  max-width: 600px; /* Adjust as needed */
  margin: 0 auto;
}
</style>
